from ..malody.cookie import MalodyCookieManager
from ..malody.gen_image import ma
from .._register import register_command
import threading

cookie_manager = MalodyCookieManager()

def start_keepalive():
    t = threading.Thread(target=cookie_manager.run_keepalive_loop, daemon=True)
    t.start()

start_keepalive()

##这个马老弟爬虫是小时候写的，偶然发现电脑里有存远古代码，翻出来发现还能用，就装上了，不准笑
##这个马老弟爬虫是小时候写的，偶然发现电脑里有存远古代码，翻出来发现还能用，就装上了，不准笑

@register_command("/ma")
async def malody_command(client):
    args = client.msg.split(" ")
    if len(args) < 2:
        await client.reply("请输入用户名")
        return True

    user_name = args[1]
    cookie = cookie_manager.get_cookie()

    if not cookie:
        await client.reply("没有有效的 Cookie，手动在 cookie.json 中设置")
        return True

    try:
        ma(user_name, cookie)
        await client.reply(image='./data/cache/send/malody.png')
    except Exception as e:
        import traceback
        tb_str = ''.join(traceback.format_exception(type(e), e, e.__traceback__))
        lineno = e.__traceback__.tb_lineno
        print(f"发生未知错误:\n{tb_str}\n错误行号: {lineno}")
        await client.reply("❌ 生成失败，请查看日志。")

    return True
